/**
 * 格式化路由
 */
import { RouteRecordRaw } from 'vue-router'
import router, { routeComponentMap } from "../router";

// 把后端传过来的路由格式成前端需要的路由
export const formatRoutes = (menuList: any[] = []) => {
    const formatTree = (allMenu: any[], parentId: number): any => {
        return allMenu.filter(menuItem => menuItem.parentId == parentId).map(item => {
            let children = formatTree(allMenu.filter(menuItem => menuItem.parentId !== parentId), item.id);
            return {
                meta: { title: item.label, icon: item.icon },
                name: item.name,
                ...routeComponentMap[item.name],
                children: children.length > 0 ? children : null
            }
        })
    }
    return formatTree(menuList, 0);
}

// addRoutes 已废弃，手动封装一个。
export const addRoutes = (routes: Array<RouteRecordRaw>): void => {
    const deepAddRoute = (parentRoute: RouteRecordRaw | null, routes: Array<RouteRecordRaw>) => {
        routes.forEach((route: RouteRecordRaw) => {
            let currentParentRoute = route;
            if (!parentRoute) {
                router.addRoute(route);
            } else {
                route.path = parentRoute.path + route.path;
                router.addRoute(parentRoute.name || '', route);
            }
            if (route.children && route.children.length > 0) {
                deepAddRoute(currentParentRoute, route.children)
            }
        })
    }
    deepAddRoute(null, routes)
}
